<?php


namespace App\Http\Middleware;


use Swoft\Bean\Annotation\Mapping\Bean;
use Swoft\Bean\Annotation\Mapping\Inject;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Swoft\Console\Helper\Show;
use Swoft\Http\Server\Contract\MiddlewareInterface;

/**
 * request 日志
 * @Bean()
 * Class LogMiddleware
 * @package App\Http\Middleware
 */
class LogMiddleware implements MiddlewareInterface
{
    /**
     * @Inject("redisLog.pool")
     * @var
     */
    private $redis;


    /**
     *
     * @param ServerRequestInterface $request
     * @param RequestHandlerInterface $handler
     * @return ResponseInterface
     */
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        $request->run_start = microtime(true);

        $request->serial_number = $request->getHeaderLine('serial-number');
        $request->phone_model = $request->getHeaderLine('phone-model');
        $request->device = $request->getHeaderLine('device');
        $request->company = $request->getHeaderLine('company');
        $request->timestamp = $request->getHeaderLine('timestamp');
        $request->system_version = $request->getHeaderLine('system-version');
        $request->lang = $request->getHeaderLine('lang');
        $request->version = $request->getHeaderLine('version');

        $response = $handler->handle($request);
        $log = $this->logInfo($request);
        //记录日志
        $this->redis->rpush('vaffle-business', JSON($log));
        return $response;
    }

    /**
     * 日志所需记录数据
     * @param $request
     * @return array
     */
    public function logInfo($request)
    {
        return [
            'domain' => 'swoft',
            'serv_timestamp' => time(),
            'serverip' => $request->getServerParams()['server_addr'],
            'env' => env('LOG_ENV','local'),
            'time' => date('Y-m-d H:i:s', time()) ,
            'ip' => $request->getHeaderLine('x-forwarded-for'),
            'url' =>  $request->getServerParams()['request_uri'],
            'body' => $request->getParsedBody(),
            'headers'  =>  $request->getHeaders()
        ];
    }

}